<?php
namespace app\admin\controller;
use app\admin\controller\Common;
use think\Db;
use think\Request;
use think\Session;
use app\admin\model\Choice;
class Single extends Common
{
    public function add()
    {
        if(Request::instance()->isGet()){
            $id = Request::instance()->param('id');
            if($id){
                $choice = Choice::get($id);
                $answer = $choice->answer;
                $answerarr = explode(',',$answer);
                $this->assign("answerarr",$answerarr);
                $this->assign("cdata",$choice);
                return $this->fetch('edit');
            }else{
                return $this->fetch();
            }
        }
    }

    //添加选择题
    public function doAdd(){
    	if (Request::instance()->isPost()) {
            $data = Request::instance()->post();
            $sdata['creater'] = Session::get('id');
            $sdata['degree'] = $data['degree'];
            $sdata['title'] = $data['title'];
            $sdata['optionA'] = $data['optionA'];
            $sdata['optionB'] = $data['optionB'];
            $sdata['optionC'] = $data['optionC'];
            $sdata['optionD'] = $data['optionD'];
            $sdata['analysis'] = $data['analysis'];
            $sdata['score'] = $data['score'];

            //判断answerABCD是否存在   1-A 2-B 3-C 4-D
            $sdata['answer'] = '';
            if (isset($data['answerA'])) {
                $sdata['answer'] .= $data['answerA'] == 'on' ? '1,' : '';
            }
            if (isset($data['answerB'])) {
                $sdata['answer'] .= $data['answerB'] == 'on' ? '2,' : '';
            }
            if (isset($data['answerC'])) {
                $sdata['answer'] .= $data['answerC'] == 'on' ? '3,' : '';
            }
            if (isset($data['answerD'])) {
                $sdata['answer'] .= $data['answerD'] == 'on' ? '4,' : '';
            }
            // dump($sdata['answer']);
            // dump($answer);
            //判断是单选还是多选或者不定项
            //单选只有一个答案正确
            //多选最少有两个最多有四个
            //不定项最后有一个最多有四个
            // 1-单选 2-多选 3-不定项
            $tanswer = trim($sdata['answer'],',');
            $num = substr_count($tanswer,',');
            $snum = strlen($sdata['answer']);
            // var_dump($tanswer);
            // var_dump($num);
            // var_dump($snum);
            switch ($data["category"])
            {
                case 1:
                    if ($snum < 1 || $num > 0) {
                        $this->error('单项选择题只能有一个答案');
                    }
                    break;
                case 2:
                    if ($num < 1 || $num > 3) {
                        $this->error('多项选择题最少有两个最多有四个答案');
                    }
                    break;
                case 3:
                    if ($snum < 1 || $num > 3) {
                        $this->error('不定项选择题最少有一个最多有四个答案');
                    }
                    break;
                default:
                    $this->error('选择题类别错误');
            }
            $sdata['answer'] = $tanswer;
            $sdata['category'] = $data["category"];
            $choice = new Choice;
            if($data['id']){
                //编辑
                $result = $choice->save($sdata,['id' => $data['id']]);
                if($result){
                    $this->success('更新成功','Question/qlist');
                }else{
                    $this->error('更新失败');
                }
            }else{
                //新增
                $choice->data($sdata);
                if ($choice->save()) {
                    $this->success('添加成功','Question/qlist');
                }else{
                    $this->error('添加失败');
                }
            }
    	}else{
    		$this->error('请求不合法');
    	}
    }
     /**
     * 随机获取指定数量的单选题
     * @access public
     * @param $num 数量
     * @param $category 类型
     * @param $degree 难度
     * return string
     */
    public static function getSingle($num,$category,$degree=null){
    	$choiceid = '';

    	//区分难度的试题的数量
    	$idarr = self::getValueByColumn('id',$category,$degree);
    	//除了指定难度的试题的数量
	    $idarrno = self::getValueByColumnRe('id',$category,$degree);
    	$idarrnum = count($idarr);
		$bkey = count($idarrno)-1;
    	if ($idarrnum > 0) {
    		//如果难度系数的题目不够  先把难度的取出来，然后剩下的里面取剩下的题目
		    if ($num > $idarrnum) {
		    	$choiceidarr = [];//把或者试题放进去 然后打乱顺序
		    	//符合难度的试题
		   		$allnum = $idarrnum-1;
		    	$allnumarr = range(0,$allnum);//利用range()函数产生一个数组
			    shuffle($allnumarr);//利用shuffle()函数将产生的数组随机打乱顺序
		    	for ($i=0; $i < $idarrnum; $i++) {//选取数组
		        	$choiceidarr[] = $idarr[$allnumarr[$i]];
		   		}
		   		//补得不符合难度的试题
		   		$diff = $num - $idarrnum;//需要补充的试题数量 5-3=2
		   		$allnumarra = range(0,$bkey);//利用range()函数产生一个数组
		    	shuffle($allnumarra);//利用shuffle()函数将产生的数组随机打乱顺序
				for ($i=0; $i < $diff; $i++) {//选取数组
					$index = $allnumarra[$i];
		        	$choiceidarr[] = $idarrno[$index];
		   		}
		   		
		   		shuffle($choiceidarr);
		   		$choiceid = implode(',',$choiceidarr);
		    }else{

		    	$allnum = $idarrnum-1;
		    	$allnumarr = range(0,$allnum);//利用range()函数产生一个数组
			    shuffle($allnumarr);//利用shuffle()函数将产生的数组随机打乱顺序
		    	for ($i=0; $i < $num; $i++) {//选取数组
		        	$choiceid .= $idarr[$allnumarr[$i]].',';
		   		}
		    }
    	}else{
    		//没有该难度的试题
	    	$allnumarr = range(0,$bkey);//利用range()函数产生一个数组
		    shuffle($allnumarr);//利用shuffle()函数将产生的数组随机打乱顺序
	    	for ($i=0; $i < $num; $i++) {//选取数组
	        	$choiceid .= $idarrno[$allnumarr[$i]].',';
	   		}
    	}
	    return trim($choiceid,',');
    }
     /**
     * 查询指定类型的指定难度的试题的数量
     * @access public
     * @param $category 类型
     * @param $degree 试题难度
     * return string
     */
    public static function getCount($category,$degree=null){
    	$map = [];
    	$map['category'] = $category;
    	$map['creater'] = Session::get('id');
    	if (!empty($degree)) {
    		$map['degree'] = $degree;
    	}
    	$num = Choice::where($map)->count();
    	return $num;
    }
    /**
     * 查询指定类型的指定难度的试题的id值
     * @access public
     * @param $category 类型
     * @param $degree 试题难度
     * @param $column 列名
     * return string
     */
    public static function getValueByColumn($column,$category,$degree=null){
    	$map = [];
    	$map['category'] = $category;
    	$map['creater'] = Session::get('id');
    	if (!empty($degree)) {
    		$map['degree'] = $degree;
    	}
    	$idarr = Choice::where($map)->column($column);
    	return $idarr;
    }
	/**
     * 查询指定类型的不等于指定难度的试题的id值
     * @access public
     * @param $category 类型
     * @param $degree 试题难度
     * @param $column 列名
     * return string
     */
    public static function getValueByColumnRe($column,$category,$degree){
    	$map = [];
    	$map['category'] = $category;
    	$map['creater'] = Session::get('id');
    	if (!empty($degree)) {
    		$map['degree'] = ['<>',$degree];
    	}
    	$idarr = Choice::where($map)->column($column);
    	return $idarr;
    }
    /**
     * 预览
     * @access public
     * return array
     */
    public function preview(){
        if(Request::instance()->isGet()){
            $id = Request::instance()->param('id');
            $choice = Choice::get($id);
            //处理一下答案
            $answer = $choice->answer;
            $answerarr = explode(',',$answer);
//            dump($answerarr);
            $this->assign("cdata",$choice);
            $this->assign("answerarr",$answerarr);
            return $this->fetch();
        }else{
            $this->error('请求不合法');
        }
    }

    /**
     * 删除试题
     * @access public
     * return bool
     */
    public function delsingle(){
        if(Request::instance()->isGet()){
            $id = Request::instance()->param("id");
            if($id){
                $choice = Choice::get($id);
                if($choice){
                    if($choice->paperid){
                        return $this->error("试题存在试卷,不能删除");
                    }else{
                        if(Choice::destroy($id)){
                            return $this->success("删除成功",'Question/qlist');
                        }else{
                            return $this->error("删除失败");
                        }
                    }
                }else{
                    return $this->error("要删除的数据不存在");
                }
            }else{
                return $this->error("参数错误");
            }
        }else{
            return $this->error("请求方式错误");
        }
    }
    /**
     * 根据id取出试题的详细信息
     * @access public
     * @param string $ids
     * return array
     */
    public static function getInfoById($ids){
        if($ids){
            $single = new Choice();
            $data = $single->getInfoByIds($ids);
            return $data;
        }else{
            return false;
        }
    }
}
